<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Recharge;
use App\Models\BankDetailHangzhou;
use App\Services\Bank\BankServiceManager;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class AdminRechargeController extends Controller
{
    private BankServiceManager $bankService;

    public function __construct(BankServiceManager $bankService)
    {
        $this->bankService = $bankService;
    }

    /**
     * 获取充值申请列表
     * GET /admin/recharges
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $query = Recharge::with(['tenant'])
                ->orderBy('created_at', 'desc');

            // 状态筛选
            if ($request->filled('status')) {
                $status = $request->get('status');
                if (is_array($status)) {
                    $query->whereIn('status', $status);
                } else {
                    $query->where('status', $status);
                }
            }

            // 金额范围筛选
            if ($request->filled('amount_min')) {
                $query->where('amount', '>=', $request->get('amount_min'));
            }
            if ($request->filled('amount_max')) {
                $query->where('amount', '<=', $request->get('amount_max'));
            }

            // 时间范围筛选
            if ($request->filled('date_start')) {
                $query->where('created_at', '>=', $request->get('date_start') . ' 00:00:00');
            }
            if ($request->filled('date_end')) {
                $query->where('created_at', '<=', $request->get('date_end') . ' 23:59:59');
            }

            // 搜索：充值单号、落地公司、银行账号
            if ($request->filled('search')) {
                $search = trim((string) $request->get('search'));
                $query->where(function ($q) use ($search) {
                    $q->where('recharge_number', 'like', "%{$search}%")
                      ->orWhere('landing_company', 'like', "%{$search}%")
                      ->orWhere('bank_account', 'like', "%{$search}%")
                      ->orWhereHas('tenant', function ($tenantQuery) use ($search) {
                          $tenantQuery->where('name', 'like', "%{$search}%");
                      });
                });
            }

            // 分页
            $perPage = $request->get('per_page', 20);
            $recharges = $query->paginate($perPage);

            // 添加状态统计
            $statusStats = Recharge::selectRaw('status, COUNT(*) as count')
                ->groupBy('status')
                ->pluck('count', 'status')
                ->toArray();

            return response()->json([
                'code' => 0,
                'message' => '获取成功',
                'data' => [
                    'list' => $recharges->items(),
                    'pagination' => [
                        'current_page' => $recharges->currentPage(),
                        'per_page' => $recharges->perPage(),
                        'total' => $recharges->total(),
                        'last_page' => $recharges->lastPage(),
                    ],
                    'statistics' => [
                        'status_counts' => $statusStats,
                        'total_amount' => Recharge::sum('amount'),
                        'today_count' => Recharge::whereDate('created_at', today())->count(),
                    ]
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('获取充值列表失败', [
                'error' => $e->getMessage(),
                'params' => $request->all()
            ]);

            return response()->json([
                'code' => 500,
                'message' => '获取充值列表失败',
                'data' => null
            ], 500);
        }
    }

    /**
     * 获取充值详情
     * GET /admin/recharges/{id}
     */
    public function show($id): JsonResponse
    {
        try {
            $recharge = Recharge::with(['tenant'])->find($id);

            if (!$recharge) {
                return response()->json([
                    'code' => 404,
                    'message' => '充值申请不存在',
                    'data' => null
                ], 404);
            }

            // 获取匹配的银行明细
            $matchedDetail = null;
            if ($recharge->status === Recharge::STATUS_MATCHED || $recharge->status === Recharge::STATUS_CONFIRMED) {
                $matchedDetail = BankDetailHangzhou::where('matched_recharge_id', $id)->first();
            }

            // 获取可能的匹配建议（如果未匹配）
            $matchSuggestions = [];
            if (in_array($recharge->status, [Recharge::STATUS_PENDING, Recharge::STATUS_PROCESSING])) {
                $matchSuggestions = $this->getMatchSuggestions($recharge);
            }

            return response()->json([
                'code' => 0,
                'message' => '获取成功',
                'data' => [
                    'recharge' => $recharge,
                    'matched_detail' => $matchedDetail,
                    'match_suggestions' => $matchSuggestions
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('获取充值详情失败', [
                'error' => $e->getMessage(),
                'recharge_id' => $id
            ]);

            return response()->json([
                'code' => 500,
                'message' => '获取充值详情失败',
                'data' => null
            ], 500);
        }
    }

    /**
     * 确认匹配
     * POST /admin/recharges/{id}/confirm-match
     */
    public function confirmMatch(Request $request, $id): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'bank_detail_id' => 'required|integer|exists:bank_details_hangzhou,id'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 400,
                'message' => '参数验证失败',
                'data' => $validator->errors()
            ], 400);
        }

        try {
            $bankDetailId = $request->get('bank_detail_id');
            $operatorId = auth()->id(); // 假设有管理员认证

            $result = $this->bankService->confirmMatch($id, $bankDetailId, $operatorId);

            if ($result['success']) {
                return response()->json([
                    'code' => 0,
                    'message' => '匹配确认成功',
                    'data' => $result
                ]);
            } else {
                return response()->json([
                    'code' => 400,
                    'message' => $result['error'] ?? '匹配确认失败',
                    'data' => null
                ], 400);
            }

        } catch (\Exception $e) {
            Log::error('确认匹配失败', [
                'error' => $e->getMessage(),
                'recharge_id' => $id,
                'bank_detail_id' => $request->get('bank_detail_id')
            ]);

            return response()->json([
                'code' => 500,
                'message' => '确认匹配失败',
                'data' => null
            ], 500);
        }
    }

    /**
     * 取消匹配
     * DELETE /admin/recharges/{id}/cancel-match
     */
    public function cancelMatch($id): JsonResponse
    {
        try {
            $operatorId = auth()->id(); // 假设有管理员认证

            $result = $this->bankService->cancelMatch($id, $operatorId);

            if ($result['success']) {
                return response()->json([
                    'code' => 0,
                    'message' => '取消匹配成功',
                    'data' => $result
                ]);
            } else {
                return response()->json([
                    'code' => 400,
                    'message' => $result['error'] ?? '取消匹配失败',
                    'data' => null
                ], 400);
            }

        } catch (\Exception $e) {
            Log::error('取消匹配失败', [
                'error' => $e->getMessage(),
                'recharge_id' => $id
            ]);

            return response()->json([
                'code' => 500,
                'message' => '取消匹配失败',
                'data' => null
            ], 500);
        }
    }

    /**
     * 手动执行匹配算法
     * POST /admin/recharges/run-matching
     */
    public function runMatching(Request $request): JsonResponse
    {
        try {
            $options = $request->get('options', []);

            Log::info('管理员手动执行匹配算法', [
                'operator_id' => auth('admin')->id(),
                'options' => $options
            ]);

            $result = $this->bankService->runRechargeMatching($options);

            if ($result['success']) {
                return response()->json([
                    'code' => 0,
                    'message' => '匹配算法执行成功',
                    'data' => [
                        'total_recharges' => $result['total_recharges'],
                        'matched_count' => $result['matched_count'],
                        'unmatched_count' => $result['unmatched_count'],
                        'success_rate' => $result['success_rate'],
                        'matches' => $result['matches'] ?? []
                    ]
                ]);
            } else {
                return response()->json([
                    'code' => 400,
                    'message' => $result['error'] ?? '匹配算法执行失败',
                    'data' => null
                ], 400);
            }

        } catch (\Exception $e) {
            Log::error('匹配算法执行失败', [
                'error' => $e->getMessage(),
                'operator_id' => auth()->id()
            ]);

            return response()->json([
                'code' => 500,
                'message' => '匹配算法执行失败',
                'data' => null
            ], 500);
        }
    }

    /**
     * 批量确认匹配
     * POST /admin/recharges/batch-confirm
     */
    public function batchConfirm(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'matches' => 'required|array',
            'matches.*.recharge_id' => 'required|integer|exists:recharges,id',
            'matches.*.bank_detail_id' => 'required|integer|exists:bank_details_hangzhou,id'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 400,
                'message' => '参数验证失败',
                'data' => $validator->errors()
            ], 400);
        }

        try {
            $matches = $request->get('matches');
            $operatorId = auth()->id();
            $results = [];
            $successCount = 0;

            foreach ($matches as $match) {
                $result = $this->bankService->confirmMatch(
                    $match['recharge_id'],
                    $match['bank_detail_id'],
                    $operatorId
                );

                $results[] = [
                    'recharge_id' => $match['recharge_id'],
                    'bank_detail_id' => $match['bank_detail_id'],
                    'success' => $result['success'],
                    'error' => $result['success'] ? null : ($result['error'] ?? '未知错误')
                ];

                if ($result['success']) {
                    $successCount++;
                }
            }

            return response()->json([
                'code' => 0,
                'message' => "批量确认完成，成功 {$successCount}/{count($matches)} 项",
                'data' => [
                    'total' => count($matches),
                    'success_count' => $successCount,
                    'failed_count' => count($matches) - $successCount,
                    'results' => $results
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('批量确认匹配失败', [
                'error' => $e->getMessage(),
                'matches' => $request->get('matches')
            ]);

            return response()->json([
                'code' => 500,
                'message' => '批量确认匹配失败',
                'data' => null
            ], 500);
        }
    }

    /**
     * 获取匹配建议
     */
    private function getMatchSuggestions(Recharge $recharge, int $limit = 5): array
    {
        try {
            // 获取未匹配的银行明细
            $unmatchedDetails = BankDetailHangzhou::unmatched()
                ->income()
                ->orderBy('transaction_datetime', 'desc')
                ->limit(50) // 限制查询范围
                ->get();

            $suggestions = [];

            foreach ($unmatchedDetails as $detail) {
                // 简化的匹配度计算
                $confidence = $this->calculateSimpleConfidence($recharge, $detail);

                if ($confidence >= 0.3) { // 最低阈值
                    $suggestions[] = [
                        'bank_detail' => $detail,
                        'confidence' => round($confidence, 3),
                        'match_reasons' => $this->getMatchReasons($recharge, $detail, $confidence)
                    ];
                }
            }

            // 按置信度排序并限制数量
            usort($suggestions, function ($a, $b) {
                return $b['confidence'] <=> $a['confidence'];
            });

            return array_slice($suggestions, 0, $limit);

        } catch (\Exception $e) {
            Log::error('获取匹配建议失败', [
                'error' => $e->getMessage(),
                'recharge_id' => $recharge->id
            ]);
            return [];
        }
    }

    /**
     * 简化的置信度计算
     */
    private function calculateSimpleConfidence(Recharge $recharge, BankDetailHangzhou $detail): float
    {
        $score = 0;

        // 金额匹配 (40%)
        if ($recharge->amount == $detail->amt) {
            $score += 0.4;
        } elseif (abs($recharge->amount - $detail->amt) / max($recharge->amount, $detail->amt) <= 0.05) {
            $score += 0.2;
        }

        // 时间匹配 (30%)
        $timeDiff = abs($recharge->created_at->diffInHours($detail->transaction_datetime));
        if ($timeDiff <= 1) {
            $score += 0.3;
        } elseif ($timeDiff <= 24) {
            $score += 0.2;
        } elseif ($timeDiff <= 72) {
            $score += 0.1;
        }

        // 银行账号匹配 (20%)
        if ($recharge->bank_account && $recharge->bank_account === $detail->bank_acc) {
            $score += 0.2;
        }

        // 银行名称匹配 (10%)
        if ($recharge->bank_name && $detail->opp_acc_bank &&
            strpos($detail->opp_acc_bank, $recharge->bank_name) !== false) {
            $score += 0.1;
        }

        return $score;
    }

    /**
     * 获取匹配原因说明
     */
    private function getMatchReasons(Recharge $recharge, BankDetailHangzhou $detail, float $confidence): array
    {
        $reasons = [];

        if ($recharge->amount == $detail->amt) {
            $reasons[] = '金额完全匹配';
        } elseif (abs($recharge->amount - $detail->amt) <= 5) {
            $reasons[] = '金额接近匹配';
        }

        $timeDiff = abs($recharge->created_at->diffInHours($detail->transaction_datetime));
        if ($timeDiff <= 1) {
            $reasons[] = '时间非常接近';
        } elseif ($timeDiff <= 24) {
            $reasons[] = '时间较为接近';
        }

        if ($recharge->bank_account === $detail->bank_acc) {
            $reasons[] = '银行账号匹配';
        }

        if ($confidence >= 0.8) {
            $reasons[] = '高置信度匹配';
        } elseif ($confidence >= 0.6) {
            $reasons[] = '中等置信度匹配';
        }

        return $reasons;
    }
}